import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../components/Login.vue'
import Home from '../components/Home.vue'
import Welcome from '../components/Welcome.vue'
import User from '../components/user/User.vue'
import List from '../components/goods/List.vue'
Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    { path: '/', redirect: '/login' },
    { path: '/login', component: Login },
    {
      path: '/home',
      component: Home,
      // 重定向welcome
      redirect: '/welcome',
      children: [
        { path: '/welcome', component: Welcome },
        // 通过路由展示用户组件
        { path: '/users', component: User },
        { path: '/goods', component: List }
      ]
    }
  ]
})

// 挂在路由导航守卫
router.beforeEach((to, from, next) => {
  // to将要访问的路径
  // from代表从哪个路径跳转
  // next是一个函数,表示放行
  // next() 放行

  // 当从登陆页访问,可放行
  if (to.path === '/login') return next()
  // 获得token
  const tokenStr = window.sessionStorage.getItem('token')
  // 如果没有token,不可放行,跳转登录页
  if (!tokenStr) return next('/login')
  // 反之放行
  next()
})

export default router
